package dirdao

import (
	"errors"
	"fmt"
	"hft/Database/admin/file"
	"hft/e"
	"hft/global"

	"gorm.io/gorm"
)

// 寻找父目录
func FindPDir(account_id int, pid int, tx *gorm.DB) (link string, err error) {
	var PDir *file.Dir
	err = tx.Model(&file.Dir{}).Where("account_id = ?", account_id).Scopes(FindDirLink(pid, tx)).First(&PDir).Error
	if err != nil {
		return "", errors.New(e.DirNotExist)
	}
	return PDir.Link, nil
}

func FindDirLink(id int, db *gorm.DB) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if id == 1 {
			return db.Where("link = ?", ",")
		} else {
			return db.Where("id = ?", id)
		}
	}
}

// 找出符合该目录以及所有子孙目录
func FindAllDirBelongThisDir(account_id uint, id int, db *gorm.DB) (ids []int, err error) {
	var root *file.Dir
	var list []*file.Dir
	var idsList []int
	err = db.Transaction(func(tx *gorm.DB) error {
		err = tx.Where("account_id = ?", account_id).Scopes(FindDirLink(id, global.OC_DB)).First(&root).Error
		if err != nil {
			return errors.New(e.DirNotExist)
		}

		err = tx.Where("link LIKE ?", fmt.Sprintf("%v%%", root.Link)).Where("account_id", account_id).Find(&list).Error
		if err != nil {
			return errors.New(e.ErrorInfo)
		}
		return nil
	})

	if err != nil {
		return nil, err
	}

	for _, v := range list {
		idsList = append(idsList, int(v.ID))
	}

	return idsList, nil
}

// 校验 文件大小是否超出限制
